<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="党组织名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入党组织名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="党组织类型" prop="partyType">
              <el-select v-model="queryParams.partyType" placeholder="请选择党组织类型" clearable>
                <el-option v-for="dict in party_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['biz:party:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="partyTableRef"
        v-loading="loading"
        :data="partyList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="党组织名称" prop="name" />
        <el-table-column label="党组织地址" align="center" prop="address" />
        <el-table-column label="图片" align="center" prop="imageUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="党组织类型" align="center" prop="partyType">
          <template #default="scope">
            <dict-tag :options="party_type" :value="scope.row.partyType" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:party:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['biz:party:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:party:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改党组织对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="partyFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="党组织名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入党组织名称" />
        </el-form-item>
        <el-form-item label="党组织地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入党组织地址" />
        </el-form-item>
        <el-form-item label="党组织类型" prop="partyType">
          <el-select v-model="form.partyType" placeholder="请选择党组织类型">
            <el-option v-for="dict in party_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父编号" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="partyOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择父编号"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="简介" prop="desc">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入内容" :rows="6" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <imageUpload v-model="form.image" />
        </el-form-item>
        <el-form-item label="地图">
          <map-container ref="mapRef" containerStyle="width: 100%; height: 200px" @updateCoordinates="handleCoordinatesUpdate" @load="mapLoad" />
        </el-form-item>
        <el-form-item label="精度" prop="lon">
          <el-input v-model="form.lon" placeholder="请输入精度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Party" lang="ts">
import { listParty, getParty, delParty, addParty, updateParty } from '@/api/biz/party';
import { PartyVO, PartyQuery, PartyForm } from '@/api/biz/party/types';
import MapContainer from '@/views/biz/components/mapContainer/index.vue';

type PartyOption = {
  id: number;
  name: string;
  children?: PartyOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { party_type } = toRefs<any>(proxy?.useDict('party_type'));

const partyList = ref<PartyVO[]>([]);
const partyOptions = ref<PartyOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const mapRef = ref(null);

const queryFormRef = ref<ElFormInstance>();
const partyFormRef = ref<ElFormInstance>();
const partyTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PartyForm = {
  id: undefined,
  name: undefined,
  address: undefined,
  image: undefined,
  partyType: undefined,
  parentId: undefined,
  desc: undefined,
  lon: undefined,
  lat: undefined
};
const data = reactive<PageData<PartyForm, PartyQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    address: undefined,
    image: undefined,
    partyType: undefined,
    parentId: undefined,
    desc: undefined,
    lon: undefined,
    lat: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '党组织名称不能为空', trigger: 'blur' }],
    partyType: [{ required: true, message: '党组织类型不能为空', trigger: 'change' }],
    parentId: [{ required: true, message: '父编号不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询党组织列表 */
const getList = async () => {
  loading.value = true;
  const res = await listParty(queryParams.value);
  const data = proxy?.handleTree<PartyVO>(res.data, 'id', 'parentId');
  if (data) {
    partyList.value = data;
    loading.value = false;
  }
};

/** 查询党组织下拉树结构 */
const getTreeselect = async () => {
  const res = await listParty();
  partyOptions.value = [];
  const data: PartyOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<PartyOption>(res.data, 'id', 'parentId');
  partyOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  partyFormRef.value?.resetFields();
  if (mapRef.value) {
    mapRef.value.clearPoint();
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: PartyVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加党组织';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(partyList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: PartyVO[], status: boolean) => {
  data.forEach((item) => {
    partyTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: PartyVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getParty(row.id);
  Object.assign(form.value, res.data);
  
  dialog.visible = true;
  dialog.title = '修改党组织';

  await nextTick()
  if (form.value.lat && form.value.lon) {
    mapRef.value.setPoint(form.value.lon, form.value.lat);
  }
};

/** 提交按钮 */
const submitForm = () => {
  partyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateParty(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addParty(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: PartyVO) => {
  await proxy?.$modal.confirm('是否确认删除党组织编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delParty(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 处理地图坐标更新 */
const handleCoordinatesUpdate = (coordinates) => {
  form.value.lon = coordinates.longitude;
  form.value.lat = coordinates.latitude;
};

const mapLoad = () => {
  mapRef.value.enableDrawPoint();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: 120px;
}
</style>
